﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
using TyMES.ViewModel.Record.RepairRecordVMs;
using TyMES.Model.Record;
using System.Threading.Tasks;
using TyMES.Communication.Request;
using TyMES.Services;
using TyMES.Communication;
using TyMES.Model.BaseInformation;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.CSharp.Syntax;


namespace TyMES.Controllers
{
    [Area("Record")]
    [AuthorizeJwtWithCookie]
    [ActionDescription("返修信息记录表")]
    [ApiController]
    [Route("api/RepairRecord")]
	public partial class RepairRecordController : BaseApiController
    {
        private readonly PassStationService passStationService;

        public RepairRecordController(PassStationService passStationService)
        {
             this.passStationService = passStationService;
        }

        [ActionDescription("Sys.Search")]
        [HttpPost("Search")]
		public IActionResult Search(RepairRecordSearcher searcher)
        {
            if (ModelState.IsValid)
            {
                var vm = Wtm.CreateVM<RepairRecordListVM>(passInit: true);
                vm.Searcher = searcher;
                return Content(vm.GetJson());
            }
            else
            {
                return BadRequest(ModelState.GetErrorJson());
            }
        }

        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public RepairRecordVM Get(string id)
        {
            var vm = Wtm.CreateVM<RepairRecordVM>(id);
            return vm;
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("Add")]
        public IActionResult Add(RepairRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                vm.DoAdd();
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("Sys.Edit")]
        [HttpPut("Edit")]
        public IActionResult Edit(RepairRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                vm.DoEdit(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }

		[HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete(string[] ids)
        {
            var vm = Wtm.CreateVM<RepairRecordBatchVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }


        [ActionDescription("Sys.Export")]
        [HttpPost("ExportExcel")]
        public IActionResult ExportExcel(RepairRecordSearcher searcher)
        {
            var vm = Wtm.CreateVM<RepairRecordListVM>();
            vm.Searcher = searcher;
            vm.SearcherMode = ListVMSearchModeEnum.Export;
            return vm.GetExportData();
        }

        [ActionDescription("Sys.CheckExport")]
        [HttpPost("ExportExcelByIds")]
        public IActionResult ExportExcelByIds(string[] ids)
        {
            var vm = Wtm.CreateVM<RepairRecordListVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = new List<string>(ids);
                vm.SearcherMode = ListVMSearchModeEnum.CheckExport;
            }
            return vm.GetExportData();
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<RepairRecordImportVM>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(RepairRecordImportVM vm)
        {
            if (vm!=null && (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData()))
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm?.EntityList?.Count ?? 0);
            }
        }

        [ActionDescription("单个返修数据查询")]
        [HttpPost("GetSingleRepairData")]
        public async Task<RepairRequest.AllRepairInfo> GetSingleRepairData(RepairRequest.request request)
        {
            RepairRequest.AllRepairInfo allRepairInfo = new RepairRequest.AllRepairInfo();
            allRepairInfo.RepairMaterialInfos = new List<RepairRequest.RepairInfo>();
            StationLogRecord stationLog = new StationLogRecord();
            try
            {
                var QXRegex = DC.Set<CustomConfig>().Where(x => x.customProperty == "QXRegex").FirstOrDefault()?.propertyValue;
                if (QXRegex == null)
                {
                    await passStationService.stationlogadd(stationLog, request.LineCode, request.StationCode, request.TZMaterialCode, "bad", "请先维护自定义参数表中的用于扫码进站的前箱正则");
                    return allRepairInfo;
                }
                var TZRegex = DC.Set<CustomConfig>().Where(x => x.customProperty == "TZRegex").FirstOrDefault()?.propertyValue;
                if (TZRegex == null)
                {
                    await passStationService.stationlogadd(stationLog, request.LineCode, request.StationCode, request.TZMaterialCode, "bad", "请先维护自定义参数表中的用于扫码进站的电机正则");
                    return allRepairInfo;
                }

                if (Regex.IsMatch(request.TZMaterialCode, QXRegex)|| Regex.IsMatch(request.TZMaterialCode, TZRegex))
                {

                    var SN = DC.Set<MaterialBindRecord>().Where(x => x.AssemblyMaterialSn == request.TZMaterialCode).OrderByDescending(x => x.ID).FirstOrDefault()?.SnNumber;
                    if (SN == null)
                    {
                        await passStationService.stationlogadd(stationLog, request.LineCode, request.StationCode, request.TZMaterialCode, "bad", "此前箱或电机"+request.TZMaterialCode+"未执行过上线绑定");
                        return allRepairInfo;
                    }

                    allRepairInfo.SN = SN;
                    var MaterialInfos = await passStationService.UIMaterialRecords(SN);
                    foreach (var MaterialInfo in MaterialInfos)
                    {
                        RepairRequest.RepairInfo repairInfo = new RepairRequest.RepairInfo();
                        repairInfo.stationCode = MaterialInfo.stationId;
                        repairInfo.materialCode = MaterialInfo.materialCode;
                        repairInfo.materialName = MaterialInfo.materialName;
                        repairInfo.AssembleSN = MaterialInfo.materialSN;
                        allRepairInfo.RepairMaterialInfos.Add(repairInfo);
                    }
                }
                else
                    await passStationService.stationlogadd(stationLog, request.LineCode, request.StationCode, request.TZMaterialCode, "bad", "请扫电机码或前箱码，其余单体物料解绑请切换模式");

                return allRepairInfo;
            }
            catch (Exception ex)
            {
                return allRepairInfo;
            }
        }


        [ActionDescription("单体物料解绑")]
        [HttpPost("LooseSingleMaterial")]
        public async Task<RepairRequest.AllRepairInfo> LooseSingleMaterial(RepairRequest.request request)
        {
            RepairRequest.AllRepairInfo allRepairInfo = new RepairRequest.AllRepairInfo();
            allRepairInfo.RepairMaterialInfos = new List<RepairRequest.RepairInfo>();
            StationLogRecord stationLog = new StationLogRecord();
            try
            {
                var bindinfo = DC.Set<MaterialBindRecord>().Where(x=>x.AssemblyMaterialSn==request.TZMaterialCode).FirstOrDefault();
                if (bindinfo == null)
                {
                    await passStationService.stationlogadd(stationLog, request.LineCode, request.StationCode, request.TZMaterialCode, "bad", "单体物料"+request.TZMaterialCode+"未执行绑定");
                    return allRepairInfo;
                }
                bindinfo.AssemblyMaterialSn = bindinfo.AssemblyMaterialSn+"unbind";
                DC.SaveChanges();
                await passStationService.stationlogadd(stationLog, request.LineCode, request.StationCode, request.TZMaterialCode, "good", "绑定在" + bindinfo.SnNumber + "的物料" + request.TZMaterialCode + "解绑完成");
                allRepairInfo.SN = bindinfo.SnNumber;
                return allRepairInfo;
            }
            catch (Exception ex)
            {
                await passStationService.stationlogadd(stationLog, request.LineCode, request.StationCode, request.TZMaterialCode, "bad", "单体物料解绑异常"+ex.Message);
                return allRepairInfo;
            }
        }

    }
}
